﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Orion;
using ProjectMercury;
using ProjectMercury.Renderers;
using Microsoft.Xna.Framework.Input;
using ProjectMercury.Emitters;
using TomShane.Neoforce.Controls;
using Orion.Lib.Enemy;

namespace Orion.Lib
{
    public class StageScreen : GameScreenBase, ITriggerTarget
    {
        List<ParticleEffect> Effects = new List<ParticleEffect>();
        SpriteBatchRenderer renderer;
        LevelDescriptor level;
        LevelFlowManager flow;
        public List<BaseEnemy> Enemies = new List<BaseEnemy>();

        public StageScreen(LevelDescriptor _level, LevelFlowManager _flow)
            : base()
        {
            level = _level;
            flow = _flow;
        }

        public override void Initialize()
        {
            base.Initialize();
            renderer = new SpriteBatchRenderer
            {
                GraphicsDeviceService = MyGame.graphics
            };
        }

        public override void LoadContent()
        {
            if (!isLoaded)
            {
                base.LoadContent();

                try
                {
                    foreach (var item in flow.ParicleEffects)
                    {
                        Effects.Add(item);
                    }
                   
                }  catch { };
                renderer.LoadContent(MyGame.staticContent);

                MyGame.Instance.IsMouseVisible = false;
                CreateShip();
            }

            //ImageBox ib = new ImageBox(MyGame.UIManager);
            //ib.Image = flow.BackgroundImage;
            //ib.Init();
            //ib.SizeMode = SizeMode.Stretched;
            //ib.Top = 0;
            //ib.Left = 0;
            //ib.Height = MyGame.graphics.GraphicsDevice.ScissorRectangle.Height;
            //ib.Width = MyGame.graphics.GraphicsDevice.ScissorRectangle.Width;
            //= MyGame.graphics.GraphicsDevice.ScissorRectangle;
           // MyGame.UIManager.Add(ib);
        }

        Ship player1;
        private void CreateShip()
        {
            player1 = new Ship(MyGame.staticContent.Load<Texture2D>("spaceship1")) { ZIndex = -1 };
            player1.AttachWeapon(new LaserGun() { Offset = new Vector2(0, 0), Color = Color.Red });
            player1.AttachWeapon(new LaserGun() { Offset = new Vector2(50, 0) });
        }

        
        TimeSpan lastFrameProcessed;
        int framesProcessed = 0;
        TimeSpan firstUpdTime;
        public override void Update(GameTime gameTime)
        {
            if (firstUpdTime.TotalMilliseconds == 0)
                firstUpdTime = gameTime.TotalGameTime;
            //Process Frames.. 
            var frame = (from f in flow.Frames where f.Time > lastFrameProcessed && f.Time <= (gameTime.TotalGameTime - firstUpdTime) select f).FirstOrDefault();
            if(frame != null)
            {
                lastFrameProcessed = frame.Time;
                framesProcessed++;
                ProcessFrame(frame);
            }
           

            //Update Player
            #warning //TODO  move to separate class
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            var ms = Mouse.GetState();

            //  mouseEffect.Update(dt);
            foreach (var item in Effects)
            {
                item.Trigger(new Vector2(MyGame.graphics.GraphicsDevice.ScissorRectangle.Width / 2, 0));
                item.Update(dt);
                (item[0] as LineEmitter).Length = MyGame.graphics.GraphicsDevice.ScissorRectangle.Width * 3;
            }
            //mouseEffect[0].Modifiers.Add(new ProjectMercury.Modifiers.ScaleModifier() { InitialScale = Game.GetZoomFactor, UltimateScale = Game.GetZoomFactor });
            if (player1 != null)
            {
                player1.PossitionX = ms.X > 0 && ms.X < MyGame.graphics.GraphicsDevice.ScissorRectangle.Width - player1.Width ? ms.X :
                    (ms.X > 0 ? MyGame.graphics.GraphicsDevice.ScissorRectangle.Width - player1.Width : 0);
                player1.PossitionY = ms.Y > 0 && ms.Y < MyGame.graphics.GraphicsDevice.ScissorRectangle.Height - player1.Height ? ms.Y :
                    (ms.Y > 0 ? MyGame.graphics.GraphicsDevice.ScissorRectangle.Height - player1.Height : 0);

                player1.Update(gameTime);
            }

            //Update Enemies
            foreach (var item in Enemies)
            {
                item.Update(gameTime);
            }

            base.Update(gameTime);
        }

        private void ProcessFrame(dynamic frame)
        {
            frame.Action.ActFrame(this);
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
        {
            Begin();
            GraphicsDevice.Clear(Color.Black);
            this.Draw(flow.BackgroundImage, MyGame.graphics.GraphicsDevice.ScissorRectangle, Color.White);

            base.Draw(gameTime);
           
            //GraphicsDevice.DepthBufferEnable = true;
            //GraphicsDevice.AlphaBlendEnable = false;
            //GraphicsDevice.AlphaTestEnable = false;
    //            AlphaBlendEnable is set to true.
    //AlphaTestEnable is set to false.
    //DepthBufferEnable is set to false.
    //DepthBufferWriteEnable is set to false.
          
            End();

            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            renderer.LoadContent(MyGame.staticContent);
            foreach (var item in Effects)
            {
                renderer.RenderEffect(item);
            }
            Begin();

            foreach (var item in Enemies)
            {
                item.Draw(gameTime);
            }

            if (player1 != null)
                player1.Draw(gameTime);
            End();
        
        }

        
    }
}
